"""
图片管理序列化器
"""

from rest_framework import serializers
from goods.models import SKUImage,SKU
from fdfs_client.client import Fdfs_client
from django.conf import settings

from rest_framework.exceptions import ValidationError

# 新建图片可选sku
class SKUSimpleModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = [
            'id',
            'name'
        ]

class ImageModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKUImage
        fields = [
            'id',
            'sku', # sku是关联主表对象，默认映射的类型是PrimaryKeyRelatedFiel序列化结果就是sku的id值
            'image' # image是ImageField类型字段，序列化的结果是存储后端url()函数返回的结果
        ]

    # 在校验的过程中介入，实现上传图片到fdfs业务
    # 注意：在有效校验过程中介入对数据对修改，会同时影响到后续对新建和更新
    # def validate(self, attrs):
    #     # (1)、获取图片数据
    #     f = attrs.get('image')
    #     data = f.read()
    #     # (2)、上传图片
    #     conn = Fdfs_client(settings.FDFS_PATH)
    #     res = conn.upload_by_buffer(data)
    #     if res['Status'] != 'Upload successed.':
    #         raise ValidationError('fdfs上传失败！')
    #     file_id = res['Remote file_id']
    #     # (3)、把有效数据中的image字段设置为文件id
    #     attrs['image'] = file_id
    #
    #     return attrs


    # 在新建的过程中介入，实现上传图片到fdfs业务
    # def create(self, validated_data):
    #     # (1)、提取图片数据
    #     f = validated_data.get('image') # image字段经过类型校验之后是一个文件对象
    #     data = f.read()
    #     # (2)、上传图片fdfs
    #     conn = Fdfs_client(settings.FDFS_PATH)
    #     res = conn.upload_by_buffer(data)
    #     if res['Status'] != 'Upload successed.':
    #         # 上传失败
    #         raise ValidationError('上传fdfs失败！')
    #     file_id = res['Remote file_id']
    #
    #     # (3)、新建SKUImage对象保存数据库
    #     image = SKUImage.objects.create(
    #         sku=validated_data.get('sku'),
    #         image=file_id
    #     )
    #
    #     return image






